<template>
  <!-- 面包屑 -->
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>我的</el-breadcrumb-item>
      <el-breadcrumb-item>个人信息</el-breadcrumb-item>
      <el-breadcrumb-item><b>合同信息</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <div style="margin-left:20px">
    <el-row :gutter="10" class="mb8" >
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            @click="dialogAddState=true"
        ><el-icon><Plus /></el-icon>新增</el-button>
      </el-col>
    </el-row>
  </div>
<!--  <el-button style="background-color: pink" @click="dialogAddState=true">添加</el-button>-->
  <!--  数据表格-->
  <div style="margin-left:20px">
    <el-table :data="blogInfo" stripe border style="width: 100%"
    >
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="contract_number" label="合同编号"  />
      <el-table-column prop="identity" label="身份证号"  />
      <el-table-column prop="phonenumber" label="联系电话"  />
      <el-table-column prop="zip" label="邮编"  />
      <el-table-column prop="newrenewal" label="新/续签"  />
      <el-table-column prop="resident_address" label="常驻地址"  />
      <el-table-column prop="place_domicile" label="户籍所在地"  />
      <el-table-column prop="correspondence_address" label="通讯地址"  />
      <el-table-column prop="post" label="岗位"  />
      <el-table-column prop="type_contract" label="合同类型"  />
      <el-table-column prop="contract_begintime" label="合同开始时间"  />
      <el-table-column prop="contract_endtime" label="合同结束时间"  />
      <el-table-column prop="tryouttime" label="试用期限"  />
      <el-table-column label="电子签名">
        <template v-slot="scope">
          <!-- 使用 v-if 检查 scope.row.namecard 是否存在 -->
          <img v-if="scope.row.namecard" :src="scope.row.namecard" alt="签名"  style="width: 140%"/>
          <!-- 如果没有签名数据，可以显示一个默认图片或占位符 -->
          <div v-else>无签名</div>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 添加模态框 -->
  <el-dialog v-model="dialogAddState" title="添加合同" width="680">
    <div>
      <el-form ref="formAddRef" :model="formAdd" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="name" label="姓名">
              <el-input v-model="formAdd.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="tryouttime" label="使用期限">
              <el-select v-model="formAdd.tryouttime" placeholder="请选择">
                <el-option label="一年" value="一年"></el-option>
                <el-option label="两年" value="两年"></el-option>
                <el-option label="三年" value="三年"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="identity" label="身份证号">
              <el-input v-model="formAdd.identity"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="phonenumber" label="联系电话">
              <el-input v-model="formAdd.phonenumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="zip" label="邮编">
              <el-input v-model="formAdd.zip"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="newrenewal" label="新/续签">
              <el-select v-model="formAdd.newrenewal" placeholder="请选择">
                <el-option label="新签" value="新签"></el-option>
                <el-option label="续签" value="续签"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="resident_address" label="常驻地址">
              <el-cascader
                  size="large"
                  :options="regionData"
                  v-model="formAdd.resident_address"
                  @change="handleChange"
                  clearable></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="place_domicile" label="户籍地">
              <el-cascader
                  size="large"
                  :options="regionData"
                  v-model="formAdd.place_domicile"
                  @change="handleChange"
                  clearable></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="correspondence_address" label="通讯地址">
              <el-cascader
                  size="large"
                  :options="regionData"
                  v-model="formAdd.correspondence_address"
                  @change="handleChange"
                  clearable></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="post" label="岗位">
              <el-select v-model="formAdd.post" placeholder="请选择岗位">
                <el-option label="财务" value="财务"></el-option>
                <el-option label="行政" value="行政"></el-option>
                <el-option label="后勤" value="后勤"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="type_contract" label="合同类型">
              <el-select v-model="formAdd.post" placeholder="请选择合同类型">
                <el-option label="全部" value="全部"></el-option>
                <el-option label="派遣" value="派遣"></el-option>
                <el-option label="与本单位签署" value="与本单位签署"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="contract_begintime" label="合同开始时间">
              <el-date-picker
                  v-model="formAdd.contract_begintime"
                  type="date"
                  placeholder="选择日期"
                  @change="formatDate"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="contract_endtime" label="合同结束时间">
              <el-date-picker
                  v-model="formAdd.contract_begintime"
                  type="date"
                  placeholder="选择日期"
                  @change="formatDate1"></el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <el-col :span="12">
        <el-form-item label="电子签名">
          <canvas
              ref="signaturePad"
              width="300"
              height="100"
              style="border:1px solid #000;"
              @mousedown="startSign"
              @mousemove="drawSign"
              @mouseup="endSign"
              @mouseleave="endSign"
              @touchstart="startSign"
              @touchmove="drawSign"
              @touchend="endSign">
          </canvas>
        </el-form-item>
        <el-button @click="saveSignature">保存签名</el-button>
        <el-button @click="clearSignature">清除签名</el-button>
      </el-col>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAddOnReset">取消</el-button>
        <el-button type="primary" @click="submitRegisterForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import request from "@/utils/people";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import {regionData} from "element-china-area-data";
import {Plus} from "@element-plus/icons-vue";
onMounted(()=>{
  getExcontracts();
})


// 表格显示内容
const getExcontracts = () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    // 初始时不包含ID参数
  };
  //模糊查询
  if (searchFormModel.name && searchFormModel.name.trim() !== '') {
    params.name = searchFormModel.name.trim();
  }
  if (searchFormModel.post && searchFormModel.post.trim() !== '') {
    params.post = searchFormModel.post.trim();
  }
  if (searchFormModel.type_contract && searchFormModel.type_contract.trim() !== '') {
    params.type_contract = searchFormModel.type_contract.trim();
  }
  request({
    url: '/excontracts/getAll',
    method: 'get',
    params,
  }).then((req) => {
    console.log(req)
    if (200 == req.data.errorCode) {
      blogInfo.value = req.data.data.records.map(item => ({
        ...item,
      }));
      totals.value = req.data.data.total;
    }
  })
}
//搜索
const searchFormRef=ref()
const searchFormModel=reactive({
  name:'',
  post:'',
  type_contract:''
})
const searchOnSubmit=()=>{
  getExcontracts()
}

//分页
const currentPage = ref(1)
const pageSize = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const  blogInfo=ref([])
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value=val;
  getExcontracts()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value=val;
  getExcontracts()
}


///////////////////添加/////////////////////////
// 画板和签名状态
const signaturePad = ref(null);
const isDrawing = ref(false);
const signatureData = ref('');

// 表单状态和数据
const dialogAddState = ref(false);
const formAddData = {
  external_id: '',
  name: '',
  contract_number: '',
  identity: '',
  phonenumber: '',
  zip: '',
  newrenewal: '',
  resident_address: '',
  place_domicile: '',
  correspondence_address: '',
  post: '',
  type_contract: '',
  contract_begintime: '',
  contract_endtime: '',
  tryouttime: '',
  namecard: '' // 用于存储电子签名
};
const formAdd = reactive({ ...formAddData });
const addressFormRef = ref(null); // 创建一个ref引用form
// 初始化画板
onMounted(() => {
  const canvas = signaturePad.value;
  if (canvas) {
    const ctx = canvas.getContext('2d');
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 2;
  }
});

// 签名操作
const startSign = (e) => {
  const canvas = signaturePad.value;
  if (canvas && !isDrawing.value) {
    const ctx = canvas.getContext('2d');
    const rect = canvas.getBoundingClientRect();
    if (e.type.startsWith('touch')) {
      const touch = e.touches[0];
      ctx.beginPath();
      ctx.moveTo(touch.clientX - rect.left, touch.clientY - rect.top);
    } else {
      ctx.beginPath();
      ctx.moveTo(e.clientX - rect.left, e.clientY - rect.top);
    }
    isDrawing.value = true;
  }
};

const drawSign = (e) => {
  const canvas = signaturePad.value;
  if (canvas && isDrawing.value) {
    const ctx = canvas.getContext('2d');
    const rect = canvas.getBoundingClientRect();
    if (e.type.startsWith('touch')) {
      const touch = e.touches[0];
      ctx.lineTo(touch.clientX - rect.left, touch.clientY - rect.top);
    } else {
      ctx.lineTo(e.clientX - rect.left, e.clientY - rect.top);
    }
    ctx.stroke();
    e.preventDefault();
  }
};

const endSign = () => {
  isDrawing.value = false;
};

const saveSignature = () => {
  const canvas = signaturePad.value;
  if (canvas) {
    const dataURL = canvas.toDataURL();
    signatureData.value = dataURL;
    formAdd.namecard = dataURL; // 将签名数据保存到表单数据中
    ElMessage.success('签名已保存');
  }
};

const clearSignature = () => {
  const canvas = signaturePad.value;
  if (canvas) {
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    signatureData.value = '';
    formAdd.namecard = ''; // 清除签名数据
    ElMessage.success('签名已清除');
  }
};

// 提交表单
const submitRegisterForm = ()=>{
  request({
    method:'post',
    url:'/excontracts/insert',
    params:formAdd
  }).then(req=>{
    ElMessage({
      type:'info',
      message:req.data.msg
    })
    if (200 == req.data.errorCode){
      Object.assign(formAdd,formAddData)
      getExcontracts()
    }
  })
  dialogAddState.value=false;
}
const dialogAddOnReset = () => {
  Object.assign(formAdd , formAddData)
  dialogAddState.value = false
}

//////////地点设置/////////
//区域码
const hSelectedRegion = ref();
//区域名
const hSelectedRegionLabel = ref('');
//选完省市区后触发的回调函数
// 选完省市区后触发的回调函数
const handleChange = (value) => {
  hSelectedRegion.value = value;
  // 如果 value 不为空，则调用 getRegionLabel 函数获取区域名称字符串
  if (value) {
    formAdd.birthplace = getRegionLabel(value);
  } else {
    formAdd.birthplace = ''; // 如果没有选择任何区域，则清空 formAdd.place
  }
};

// 把区域码转成区域名的方法
const getRegionLabel = (value) => {
  if (!value) return '';
  let label = '';
  let data = regionData;
  for (let i = 0; i < value.length; i++) {
    const item = data.find(item => item.value === value[i]);
    if (item) {
      label += item.label;
      data = item.children;
      if (i < value.length - 1) {
        label += ' / '; // 使用 ' / ' 作为分隔符
      }
    } else {
      break;
    }
  }
  return label;
};
const formatDate=(value)=> {
  if (!value) {
    // 如果日期时间选择器的值为空，则不进行格式化
    formAdd.contract_begintime = '';
    return;
  }
  // 将日期时间字符串转换为Date对象
  const date = new Date(value);
  // 获取年、月、日、小时、分钟和秒
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');

  // 组合成所需的格式
  formAdd.contract_begintime = `${year}-${month}-${day}`;
}
const formatDate1=(value)=> {
  if (!value) {
    // 如果日期时间选择器的值为空，则不进行格式化
    formAdd.contract_endtime = '';
    return;
  }
  // 将日期时间字符串转换为Date对象
  const date = new Date(value);
  // 获取年、月、日、小时、分钟和秒
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');

  // 组合成所需的格式
  formAdd.contract_endtime = `${year}-${month}-${day}`;
}
</script>

<style scoped>
.page{
  margin-left: 40%;
}
.break{
  margin: 5px 0 0 10px;
}
.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
</style>